<script setup lang="ts">
import { ref, defineProps, defineEmits, withDefaults, watch, computed } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { getDistributeTableByIdApi, updateDistributeTableApi } from '@/api/clusters/distributeTables';
import { useI18n } from "vue-i18n";
const { t } = useI18n();

// 定义props
const props = withDefaults(defineProps<{
  visible: boolean;
  tableId: number;
}>(), {
  visible: false,
  tableId: 0
});

// 本地状态管理
const dialogVisible = ref(props.visible);
const loading = ref(false);

// Sync with prop changes
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal;
});

// Emit update event when local state changes
watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal);
});

// 定义emits
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void;
  (e: 'close'): void;
  (e: 'success'): void;
}>();

// 表单数据
const formData = ref<{
  id: number,
  timeBy: number,
  serverKey: string,
  table: string,
  flag: string,
  status: number,
  isExpire: number,
  expireTime: number,
  totalAmount: number,
  totalSize: number
}>({
  id: 0,
  timeBy: 0,
  serverKey: '',
  table: '',
  flag: '',
  status: 1,
  isExpire: 0,
  expireTime: 0,
  totalAmount: 0,
  totalSize: 0
});

// 显示用的过期时间（毫秒级）
const expireTimeDisplay = ref<number | null>(null);

// 监听表单过期时间变化，转换为显示格式（秒转毫秒）
watch(() => formData.value.expireTime, (newVal) => {
  if (newVal && newVal > 0) {
    expireTimeDisplay.value = newVal * 1000;
  } else {
    expireTimeDisplay.value = null;
  }
}, { immediate: true });

// 监听显示时间变化，转换为秒级时间戳
watch(expireTimeDisplay, (newVal) => {
  if (newVal) {
    formData.value.expireTime = Math.floor(newVal / 1000);
  } else {
    formData.value.expireTime = 0;
  }
});

// 时间格式化工具函数
const formatTimestamp = (timestamp: number) => {
  if (!timestamp || timestamp <= 0) return '';
  return new Date(timestamp * 1000).toISOString().slice(0, 19).replace('T', ' ');
};

// 时间分片规则选项
const timeByOptions = [
  { val: 1, label: t('clusters.distributeTablePage.year') },
  { val: 2, label: t('clusters.distributeTablePage.month') },
  { val: 3, label: t('clusters.distributeTablePage.day') }
];

// 状态选项
const statusOptions = [
  { val: 1, label: t('clusters.distributeTablePage.enabled') },
  { val: 0, label: t('clusters.distributeTablePage.deleted') }
];

// 过期状态选项
const expireOptions = [
  { val: 0, label: t('clusters.distributeTablePage.disabled') },
  { val: 1, label: t('clusters.distributeTablePage.enabled') }
];

// 修改visible监听，当弹窗打开时加载数据
watch(
  () => dialogVisible.value,
  async (newVal) => {
    if (newVal && props.tableId) {
      loading.value = true;
      try {
        // 调用API获取最新数据
        const response = await getDistributeTableByIdApi(props.tableId);
        if (response.code === 0) {
          formData.value = response.data.info;
          // 初始化显示时间
          if (formData.value.expireTime && formData.value.expireTime > 0) {
            expireTimeDisplay.value = formData.value.expireTime * 1000;
          } else {
            expireTimeDisplay.value = null;
          }
        } else {
          ElMessage.error(response.msg || t('clusters.distributeTablePage.getDetailFail'));
        }
      } catch (error) {
    ElMessage.error(t('clusters.distributeTablePage.getDetailFail'));
    console.error('Failed to get distribute table details:', error);
  } finally {
        loading.value = false;
      }
    }
  }
);

// 提交表单
const submitForm = async () => {
  if (loading.value) return;

  // 验证过期时间
  if (formData.value.isExpire === 1 && (!formData.value.expireTime || formData.value.expireTime <= 0)) {
    ElMessage.error(t('clusters.distributeTablePage.expireTimeRequired'));
    return;
  }
  
  if (formData.value.isExpire === 0) {
    formData.value.expireTime = -1;
  }

  loading.value = true;
  try {
    // 转换表单数据格式为API要求的格式
    const submitData = {
      timeBy: formData.value.timeBy,
      serverKey: formData.value.serverKey,
      table: formData.value.table,
      flag: formData.value.flag,
      status: formData.value.status,
      isExpire: formData.value.isExpire,
      expireTime: formData.value.expireTime
    };

    const response = await updateDistributeTableApi(formData.value.id, submitData);
    if (response.code === 0) {
      ElMessage.success(t('clusters.distributeTablePage.updateSuccess'));
      emit('update:visible', false);
      emit('success');
    } else {
      ElMessage.error(response.msg || t('clusters.distributeTablePage.updateFail'));
    }
  } catch (error) {
    ElMessage.error(t('clusters.distributeTablePage.updateFail'));
    console.error('Failed to update distribute table:', error);
  } finally {
    loading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  if (props.tableId) {
    getDistributeTableByIdApi(props.tableId).then(response => {
      if (response.code === 0) {
        formData.value = response.data.info;
      }
    });
  }
};

// 关闭弹框
const closeDialog = () => {
  emit('update:visible', false);
  emit('close');
};

// 格式化过期时间（秒级时间戳转日期时间）
const formatDuration = (timestamp: number) => {
  if (timestamp <= 0) return t('clusters.distributeTablePage.notSet');
  return new Date(timestamp * 1000).toLocaleString();
};
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="t('clusters.distributeTablePage.editTitle')"
    :draggable="true"
    @close="closeDialog"
    width="700px"
  >
    <el-form
      :model="formData"
      style="max-width: 600px; margin: 0 auto;"
      :disabled="loading"
    >
      <!-- 添加加载状态指示器 -->
<!--      <el-form-item :label="t('clusters.distributeTablePage.id')" prop="id">-->
<!--        <el-input v-model="formData.id" disabled />-->
<!--      </el-form-item>-->
      <el-form-item :label="t('clusters.distributeTablePage.serverKey')" prop="serverKey" required>
        <el-input v-model="formData.serverKey" :placeholder="t('clusters.distributeTablePage.serverKeyPlaceholder')" disabled/>
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.tableName')" prop="table" required>
        <el-input v-model="formData.table" :placeholder="t('clusters.distributeTablePage.tableNamePlaceholder')" disabled />
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.flag')" prop="flag" required>
        <el-input v-model="formData.flag" :placeholder="t('clusters.distributeTablePage.flagPlaceholder')" disabled/>
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.timeBy')" prop="timeBy" required>
        <el-select v-model="formData.timeBy" :placeholder="t('clusters.distributeTablePage.selectTimeBy')" disabled>
          <el-option
            v-for="option in timeByOptions"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.expireStatus')" prop="isExpire" required>
        <el-select v-model="formData.isExpire" :placeholder="t('clusters.distributeTablePage.selectExpireStatus')">
          <el-option
            v-for="option in expireOptions"
            :key="option.val"
            :label="option.label"
            :value="option.val"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.expireTime')" prop="expireTime" v-if="formData.isExpire === 1">
        <el-date-picker
          v-model="expireTimeDisplay"
          type="datetime"
          :placeholder="t('clusters.distributeTablePage.expireTimePlaceholder')"
          :value-format="'x'"
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
        <div class="form-hint">{{ t('clusters.distributeTablePage.expireTimeHint') }}</div>
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.totalAmount')" prop="totalAmount">
        <el-input v-model="formData.totalAmount" disabled />
      </el-form-item>
      <el-form-item :label="t('clusters.distributeTablePage.totalSize')" prop="totalSize">
        <el-input v-model="formData.totalSize" disabled />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm">{{ t('buttons.reset') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ t('buttons.submit') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
// 可以添加一些自定义样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.form-hint {
  margin-top: 5px;
  font-size: 12px;
  color: #909399;
}
</style>
